package com.xujl.task;


import android.os.Message;

import java.util.Observable;
import java.util.Observer;

/**
 * 事件发射器
 */
public class Emitter<T> implements Observer {
    private static final String TAG = "Emitter";
    public static final int ERROR = -1;
    public static final int NEXT = 0;
    public static final int FINISH = 1;
    public static final int UI = 2;
    private Task<T> task;
    private String taskId;

    public Emitter (Task<T> task, String taskId) {
        super();
        this.task = task;
        this.taskId = taskId;
        this.task.addObserver(this);
    }

    private void sendMessage (int code, T data) {
        Message message = new Message();
        message.what = code;
        message.obj = new RxMessage<>(task, data);
        RxHandler.getInstance().sendMessage(message);
    }

    private void sendObj (int code, Object obj, int objCode) {
        Message message = new Message();
        message.what = code;
        message.obj = new RxMessage<>(task).setObj(obj).setObjCode(objCode);
        RxHandler.getInstance().sendMessage(message);
    }

    private void sendObj (int code, Object obj) {
        sendObj(code, obj, 0);
    }

    public void error (Exception e) {
        sendObj(ERROR, e);
    }

    public void next (T data) {
        sendMessage(NEXT, data);
    }

    public void objNext (Object obj, int objCode) {
        sendObj(NEXT, obj, objCode);
    }

    public void objNext (Object obj) {
        sendObj(NEXT, obj);
    }

    public void finish () {
        sendObj(FINISH, null);
    }

    void runUi () {
        sendObj(UI, null);
    }


    @Override
    protected void finalize () throws Throwable {
        RxLog.d(TAG, taskId + ":即将被回收");
        super.finalize();
    }

    @Override
    public void update (Observable o, Object arg) {
        if (Task.STATE_DESTROY.equals(arg)) {
            RxLog.d(TAG, taskId + ":任务已销毁，解除Emitter绑定");
            task = null;
        }
    }
}
